package managers
{
	import com.leebrimelow.starling.StarlingPool;
	
	import objects.Alien;
	
	import starling.core.Starling;
	import starling.display.DisplayObject;
	
	import states.Play;
	
	public class AlienManager
	{
		private var _play:Play;
		private var _aliens:Vector.<Alien>
		private var _pool:StarlingPool;
		private var _count:uint;
		private var _maxAliens:uint;
		private var _moveSpeed:uint;
		private var _spawnRate:Number;
		
		public function AlienManager(play:Play)
		{
			this._play = play;
			
			_maxAliens = 100;
			_aliens = new Vector.<Alien>();
			
			_pool = new StarlingPool(Alien, _maxAliens);
			
			// add all aliens to the play class but off stage
			for each (var a:DisplayObject in _pool.items)
			{
				_play.addChild(a);
				(a as Alien).fps = Math.ceil(Math.random() * 12 + 24);
				a.x = -100;
				a.y = -100;
			}
			
			_count = 0;
			_moveSpeed = 400;
			_spawnRate = 0.02;
		}
		
		public function update(deltaSmall:Number):void
		{
			var len:int = _aliens.length - 1;
			var a:Alien;
			for (var i:int = len; i >= 0; i--)
			{
				a = _aliens[i];
				a.y += _moveSpeed * deltaSmall;
				
				if (a.y >= 800 + a.height * 0.5)
				{
					destroyAlien(a, i);
				}
			}
			
			if (Math.random() < _spawnRate)
			{
				spawn();
			}
		}
		
		public function destroyAlien(a:Alien, i:int):void
		{
			// move off stage since we are not using .removeChild()
			a.x = -100;
			a.y = -100;
			
			// return the mc to the pool
			_pool.returnSprite(a);
			
			// remove the mc from the array to prevent it executing logic
			_aliens.splice(i, 1);
			
			// remove the mc from the juggler to stop animation
			Starling.juggler.remove(a);
		}
		
		public function destroy():void
		{
			for (var i:uint = 0; i < _aliens.length; i++)
			{
				_play.removeChild(_aliens[i]);
				Starling.juggler.remove(_aliens[i])
				_aliens[i].destroy();
				_aliens.splice(i, 1);
			}
			_aliens = null;
			_pool.destroy();
			_play = null;
		}
		
		public function spawn():void
		{
			// only create aliens if the current amount of aliens on stage is less than the amount of aliens in the pool
			if (_aliens.length < _pool.items.length)
			{
				var a:Alien = _pool.getSprite() as Alien;
				Starling.juggler.add(a);
				_aliens.push(a);
				a.x = Math.random() * (800 - a.width) + a.width * 0.5;
				a.y = -50;
			}
		}
		
		public function get aliens():Vector.<Alien>
		{
			return _aliens;
		}
		
		public function set aliens(value:Vector.<Alien>):void
		{
			_aliens = value;
		}

		public function get spawnRate():Number
		{
			return _spawnRate;
		}

		public function set spawnRate(value:Number):void
		{
			_spawnRate = value;
		}

	}
}



































